package com.umeox.moto.watch.themes.widget;

import android.content.Context;
import android.os.Parcelable;
import android.util.AttributeSet;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.umeox.moto.watch.themes.skin.entity.AttrFactory;
import com.umeox.moto.watch.themes.skin.listener.IResourceChangedListener;
import com.umeox.moto.watch.themes.skin.loader.ResourceManager;


public class SkinLoaderImageView extends AppCompatImageView implements IResourceChangedListener {
    private int mResId;

    public SkinLoaderImageView(Context context) {
        this(context, null);
    }

    public SkinLoaderImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SkinLoaderImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        for (int i = 0; i < attrs.getAttributeCount(); i++) {
            String attrName = attrs.getAttributeName(i);
            String attrValue = attrs.getAttributeValue(i);
            if (attrValue.startsWith("@")) {
                try {
                    int id = Integer.parseInt(attrValue.substring(1));
                    if (AttrFactory.SRC.equals(attrName)) {
                        mResId = id;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Nullable
    @Override
    protected Parcelable onSaveInstanceState() {
        return super.onSaveInstanceState();
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {

        super.onRestoreInstanceState(state);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        ResourceManager.getInstance().attach(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        ResourceManager.getInstance().detach(this);
    }

    @Override
    public void setImageResource(int resId) {
        if (resId == 0) {
            return;
        }
        mResId = resId;
        setImageDrawable(ResourceManager.getInstance().getDrawable(resId));
    }

    @Override
    public void onResourceChanged() {
        if (mResId == 0) {
            return;
        }

        setImageResource(mResId);
    }
}
